package com.example.RxJavaDemo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;

import java.io.File;
import java.io.FileOutputStream;

import io.reactivex.Observable;


/**
 * Description :
 *
 * @author WSoBan
 * @date 2018/07/20
 */
public class FileUtils {

    private Context context;
    private String saveFolder;

    public FileUtils(Context context) {
        this.context = context;
        saveFolder = getAppSDCardDir(context) + File.separator + "images";
    }

    private String getAppSDCardDir(Context context) {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + context.getPackageName();
    }

    public Observable<Bitmap> startDownload(String url) {
        return Observable.just(url)
                .map(this::getImageBitmap);
    }

    public void startDownload(String url, ImageView imageView) {
        /*Observable.just(url)
                .map(this::getImageBitmap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        imageView.setImageBitmap(bitmap);
                    }
                });*/
    }

    private void saveBitmapToFile(Context context, String dir, String fileName, Bitmap bitmap) {
        File appDir = new File(dir);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File saveFile = new File(appDir, fileName);
        if (saveFile.exists()) {
            saveFile.delete();
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(saveFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
            //TODO 删除异常图片
            if (saveFile.exists()) {
                saveFile.delete();
            }
            return;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(saveFile.getPath()))));

    }

    private String getFileName(String url) {
        if (!TextUtils.isEmpty(url)) {
            String s = url.substring(url.lastIndexOf("/"));
            return s.substring(0, s.indexOf(".")) + ".jpg";
        } else {
            return "IMG_" + System.currentTimeMillis() + ".jpg";
        }
    }

    private Bitmap getImageBitmap(String url) {
        Bitmap bitmap = null;
        try {
            //TODO 通过Glide下载图片。注意由于Glide缓存了图片，所以会出现没有网络时也能下载成功。
            FutureTarget<Bitmap> submit = Glide.with(context)
                    .asBitmap()
                    .load(url)
                    .submit();
            bitmap = submit.get();
            if (bitmap != null) {
                // 在这里执行图片保存方法
                saveBitmapToFile(context, saveFolder, getFileName(url), bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
